package com.example.common.mybatis;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.example.common.core.constants.Constants;
import com.example.common.core.utils.ThreadLocalUtil;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @author 23050
 * @version 1.0
 * @description: MyBatis自动填充字段 配置类
 * 使用MyBatis插入更新数据时，自动添加数据
 * @date 2025/2/11 21:03
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {


    //插入时自动填充
    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject,"createTime", LocalDateTime.class,LocalDateTime.now());
        this.strictInsertFill(metaObject,"updateTime", LocalDateTime.class,LocalDateTime.now());
        this.strictInsertFill(metaObject,"createBy", Long.class, ThreadLocalUtil.get(Constants.USER_ID,Long.class));
        this.strictInsertFill(metaObject,"updateBy", Long.class, ThreadLocalUtil.get(Constants.USER_ID,Long.class));
    }

    //更新时自动填充
    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject,"updateTime", LocalDateTime.class,LocalDateTime.now());
        this.strictUpdateFill(metaObject,"updateBy", Long.class,ThreadLocalUtil.get(Constants.USER_ID,Long.class));
    }
}
